<?php

namespace app\api\controller\kuerp\pda;

use app\common\controller\Api;
use app\common\library\Ems;
use fast\Random;
use think\Config;
use think\Db;
use think\Validate;
use app\api\library\kuerp\AdminUserAuth as Auth;
use app\api\controller\kuerp\order\Sms;
use GuzzleHttp\Client;
use think\Env;
use app\api\library\kuerp\FacebookCurlHttpClient;

class User extends Api
{
    protected $noNeedLogin = '*';
    protected $noNeedRight = '*';
    protected $auth_s;

    public function _initialize()
    {
        parent::_initialize();
        $this->auth_s = new Auth();
        $token = $this->request->server('HTTP_TOKEN', $this->request->request('token', \think\Cookie::get('token')));
        $this->auth_s->init($token);
        if (!Config::get('fastadmin.usercenter')) {
            $this->error(__('User center already closed'));
        }
    }

    /**
     * 会员中心
     */
    public function index()
    {
        $this->success('', ['welcome' => $this->auth_s->nickname]);
    }

    /**
     * 会员登录
     *
     * @ApiMethod (POST)
     * @param string $account  账号
     * @param string $password 密码
     */
    public function login()
    {
        $account = $this->request->post('username');
        $password = $this->request->post('password');
        if (!$account || !$password) {
            $this->error(__('Please enter account and password'));
        }
        $ret = $this->auth_s->login($account, $password);
        if ($ret) {
            $data = ['userinfo' => $this->auth_s->getUserinfo()];
            $this->success(__('Login successful'), $data);
        } else {
            $this->error($this->auth_s->getError());
        }
    }

    /**
     * 手机验证码登录
     *
     * @ApiMethod (POST)
     * @param string $mobile  手机号
     * @param string $captcha 验证码
     */
    public function mobilelogin()
    {
        $mobile = $this->request->post('mobile');
        $captcha = $this->request->post('captcha');
        if (!$mobile || !$captcha) {
            $this->error(__('Invalid parameters'));
        }
        if (!Validate::regex($mobile, "^\d+$")) {
            $this->error(__('Mobile is incorrect'));
        }

        $sms = new Sms();

        if (!$sms->check($mobile, $captcha, 'mobilelogin')) {
            $this->error(__('Captcha is incorrect'));
        }
        $user = \app\api\model\kuerp\KuerpUser::getByMobile($mobile);
        if ($user) {
            if ($user->status != 'normal') {
                $this->error(__('Account is locked'));
            }
            //如果已经有账号则直接登录
            $ret = $this->auth_s->direct($user->id);
        } else {
            $ret = $this->auth_s->register($mobile, Random::alnum(), '', $mobile, []);
        }
        if ($ret) {
            $sms->flush($mobile, 'mobilelogin');
            $data = ['userinfo' => $this->auth_s->getUserinfo()];
            $this->success(__('Logged in successful'), $data);
        } else {
            $this->error($this->auth_s->getError());
        }
    }

    /**
     * 注册会员
     *
     * @ApiMethod (POST)
     * @param string $type     注册类型：mobile(手机号) 或 email(邮箱)
     * @param string $username 用户名
     * @param string $password 密码
     * @param string $email    邮箱
     * @param string $mobile   手机号
     * @param string $code     验证码
     */
    public function register()
    {
        $type = $this->request->post('type', 'mobile'); // 默认手机号注册
        $password = $this->request->post('password');
        $email = $this->request->post('email');
        $mobile = $this->request->post('mobile');
        $code = $this->request->post('code');

        if (!$password || !$code) {
            $this->error(__('Invalid parameters'));
        }

        // 根据注册类型进行不同的验证
        if ($type === 'email') {
            // 邮箱注册
            if (!$email) {
                $this->error(__('Email is required'));
            }
            if (!Validate::is($email, "email")) {
                $this->error(__('Email is incorrect'));
            }

            // 检查邮箱是否已存在
            if (\app\api\model\kuerp\KuerpUser::where('email', $email)->find()) {
                $this->error(__('Email already exists'));
            }

            // 验证邮箱验证码
            $ret = Ems::check($email, $code, 'register');
            if (!$ret) {
                $this->error(__('Captcha is incorrect'));
            }

            // 使用邮箱作为用户名注册
            $username = $email;
            $registerResult = $this->auth_s->register($username, $password, $email, '', []);
        } else {
            // 手机号注册（默认）
            if (!$mobile) {
                $this->error(__('Mobile is required'));
            }
            if (!Validate::regex($mobile, "^\d+$")) {
                $this->error(__('Mobile is incorrect'));
            }

            // 检查手机号是否已存在
            if (\app\api\model\kuerp\KuerpUser::where('mobile', $mobile)->find()) {
                $this->error(__('Mobile already exists'));
            }

            // 验证手机验证码
            $sms = new Sms();
            $ret = $sms->check($mobile, $code, 'register');
            if (!$ret) {
                $this->error(__('Captcha is incorrect'));
            }

            // 使用手机号作为用户名注册
            $username = $mobile;
            $registerResult = $this->auth_s->register($username, $password, $email, $mobile, []);
        }

        if ($registerResult) {

            //如果用户注册成功，则自动绑定客户
            $customer = Db::name('kuerp_customers')->where(function ($query) use ($mobile, $email) {
                $query->where('customer_mobile', $mobile)->whereOr('qq_wx_email', $email);
            })->find();

            if (!empty($customer)) {
                Db::name('kuerp_user')->where(['id' => $this->auth_s->getUserinfo()['id']])->update([
                    'binding' => '1',
                    'customers_id' => $customer['id'],
                ]);
            }
            // 注册成功后清除验证码
            if ($type === 'email') {
                Ems::flush($email, 'register');
            } else {
                $sms = new Sms();
                $sms->flush($mobile, 'register');
            }

            $data = ['userinfo' => $this->auth_s->getUserinfo()];
            $this->success(__('Sign up successful'), $data);
        } else {
            $this->error($this->auth_s->getError());
        }
    }

    /**
     * 退出登录
     * @ApiMethod (POST)
     */
    public function logout()
    {
        if (!$this->request->isPost()) {
            $this->error(__('Invalid parameters'));
        }
        $this->auth_s->logout();
        $this->success(__('Logout successful'));
    }

    /**
     * 修改会员个人信息
     *
     * @ApiMethod (POST)
     * @param string $avatar   头像地址
     * @param string $username 用户名
     * @param string $nickname 昵称
     * @param string $bio      个人简介
     */
    public function profile()
    {
        $nickname = $this->request->post('nickname');
        $avatar = $this->request->post('avatar', '', 'trim,strip_tags,htmlspecialchars');
        $data = [];
        if (!empty($nickname)) {
            $data['nickname'] = $nickname;
        }
        if (!empty($avatar)) {
            $data['avatar'] = $avatar;
        }
        $user = $this->auth_s->getUser();
        if (empty($user)) {
            $this->error(__('Please login first'));
        }
        $user = Db::name('kuerp_user')->where(['id' => $user['id']])->find();
        if (empty($user)) {
            $this->error(__('Please login first'));
        }
        $data['updatetime'] = time();
        $res = Db::name('kuerp_user')->where(['id' => $user['id']])->update($data);
        if ($res) {
            $this->success(__('Update successful'));
        }
        $this->error(__('Update failed'));
    }

    /**
     * 修改邮箱
     *
     * @ApiMethod (POST)
     * @param string $email   邮箱
     * @param string $captcha 验证码
     */
    public function changeemail()
    {
        $auth = new Auth();
        $user = $auth->getUser();
        $email = $this->request->post('email');
        $captcha = $this->request->post('captcha');
        if (!$email || !$captcha) {
            $this->error(__('Invalid parameters'));
        }
        if (!Validate::is($email, "email")) {
            $this->error(__('Email is incorrect'));
        }
        if (\app\common\model\User::where('email', $email)->where('id', '<>', $user->id)->find()) {
            $this->error(__('Email already exists'));
        }
        $result = Ems::check($email, $captcha, 'changeemail');
        if (!$result) {
            $this->error(__('Captcha is incorrect'));
        }
        $verification = $user->verification;
        $verification->email = 1;
        $user->verification = $verification;
        $user->email = $email;
        $user->save();

        Ems::flush($email, 'changeemail');
        $this->success();
    }

    /**
     * 修改手机号
     *
     * @ApiMethod (POST)
     * @param string $mobile  手机号
     * @param string $captcha 验证码
     */
    public function changemobile()
    {
        $user = $this->auth_s->getUser();
        $mobile = $this->request->post('mobile');
        $captcha = $this->request->post('captcha');
        if (!$mobile || !$captcha) {
            $this->error(__('Invalid parameters'), '', 500);
        }
        if (!Validate::regex($mobile, "^1\d{10}$")) {
            $this->error(__('Mobile format is incorrect'), '', 500);
        }
        if (\app\api\model\kuerp\KuerpUser::where('mobile', $mobile)->where('id', '<>', $user->id)->find()) {
            $this->error(__('Mobile already bound'), '', 500);
        }
        $result = (new Sms())->check($mobile, $captcha, 'changemobile');
        if (!$result) {
            $this->error(__('Captcha is incorrect'), '', 500);
        }

        $customer = Db::name('kuerp_customers')->where(['customer_mobile' => $mobile])->find();
        if (empty($customer)) {
            $this->error(__('This mobile number is not a customer yet, cannot bind'), '', 500);
        }
        Db::name('kuerp_user')->where(['id' => $user['id']])->update([
            'binding' => '1',
            'customers_id' => $customer['id'],
            'username' => $mobile,
            'mobile' => $mobile
        ]);

        $verification = $user->verification;
        $verification->mobile = 1;
        $user->verification = $verification;
        $user->username = $mobile;
        $user->mobile = $mobile;
        $user->save();

        (new Sms())->flush($mobile, 'changemobile');
        $this->success(__('bind success'), '', 200);
    }

    /**
     * 重置密码
     *
     * @ApiMethod (POST)
     * @param string $mobile      手机号
     * @param string $newpassword 新密码
     * @param string $captcha     验证码
     */
    public function resetpwd()
    {
        $type = $this->request->post("type");
        $mobile = $this->request->post("mobile");
        $email = $this->request->post("email");
        $newpassword = $this->request->post("newpassword");
        $captcha = $this->request->post("captcha");
        if (!$newpassword || !$captcha) {
            $this->error(__('Invalid parameters'), '', 500);
        }
        if ($type == 'mobile') {
            if (!Validate::regex($mobile, "^1\d{10}$")) {
                $this->error(__('Mobile format is incorrect'), '', 500);
            }
            $user = \app\api\model\kuerp\KuerpUser::getByMobile($mobile);
            if (!$user) {
                $this->error(__('User not found or mobile not bound'), '', 500);
            }
            $ret = (new Sms())->check($mobile, $captcha, 'resetpwd');
            if (!$ret) {
                $this->error(__('Captcha is incorrect'), '', 500);
            }
            (new Sms())->flush($mobile, 'resetpwd');
        } elseif ($type == 'email') {
            if (!Validate::is($email, "email")) {
                $this->error(__('Email is incorrect'));
            }
            $user = \app\api\model\kuerp\KuerpUser::getByEmail($email);
            if (!$user) {
                $this->error(__('User not found'));
            }
            $ret = Ems::check($email, $captcha, 'resetpwd');
            if (!$ret) {
                $this->error(__('Captcha is incorrect'));
            }
            Ems::flush($email, 'resetpwd');
        } else {
            $this->error(__('Type error'), '', 500);
        }
        //模拟一次登录
        $this->auth_s->direct($user->id);
        $ret = $this->auth_s->changepwd($newpassword, '', true);
        if ($ret) {
            $this->success(__('Password changed successfully'), '', 200);
        } else {
            $this->error($this->auth_s->getError(), '', 500);
        }
    }

    //绑定客户id
    public function bindCustomer(){

        $captcha = $this->request->post("captcha");
        $mobile = $this->request->post("mobile");

        $sms =  new Sms();
        $ret = $sms->check($mobile, $captcha, 'bind_customer');

        if (!$ret) {
            $this->error(__('Captcha is incorrect'),'',500);
        }else{

            $auth = new Auth();
            $token = $this->request->server('HTTP_TOKEN', $this->request->request('token', \think\Cookie::get('token')));
            $auth->init($token);

            $user = $auth->getUserinfo();
            if(!isset($user['id'])){
                $this->error(__('Please login first'),'',250);
            }
            $data['user_id'] = $user['id'];

            $user = Db::name('kuerp_user')->where(['id'=>$data['user_id']])->find();
            if(empty($user)){
                $this->error(__('User not found'),'',500);
            }else if($user['binding']!=2){
                $this->error(__('This user is already bound'),'',500);
            }else{
                $customer = Db::name('kuerp_customers')->where(['customer_mobile'=>$mobile])->find();
                if(empty($customer)){
                    $this->error(__('This mobile number is not a customer yet, cannot bind'),'',500);
                }
                $status = Db::name('kuerp_user')->where(['id'=>$user['id']])->update([
                    'binding'=>'1',
                    'customers_id'=>$customer['id'],
                    'username'=>$mobile,
                ]);
                if ($status){
                    $auth->direct($user['id']);
                    $this->success(__('Binding successful'), ['token'=>$auth->getToken()],200);
                }else{
                    $this->error(__('Binding failed'),'',500);
                }
            }
        }

    }

    /**
     * 通过token获取用户信息
     * @ApiMethod (POST)
     */
    public function userInfo($json = false)
    {
        $data = $this->auth_s->getUserinfo();
        $data['avatar'] = $data['avatar'] ? cdnurl($data['avatar'], true) : '';
        if ($json == true) {
            return $data;
        }
        $this->success(__('User information'), ['userinfo' => $data], '200');
    }

    /**
     * Google 登录
     *
     * @ApiMethod (POST)
     * @param string $token Google 返回的 ID Token
     */
    public function googleLogin()
    {
        $idToken = $this->request->post('token');
        if (!$idToken) {
            $this->error(__('Invalid parameters'));
        }

        // dump(Config::get('google.client_id'));exit;

        // 验证 Google ID Token
        $client = new \Google_Client(['client_id' => Config::get('google.client_id')]);
        // var_dump($client);exit;

        // var_dump(Config::get('google.guzzle'));exit;

        $client->setHttpClient(new Client(Config::get('google.guzzle')));

        $payload = $client->verifyIdToken($idToken);
        // var_dump($payload);exit;
        if (!$payload) {
            $this->error(__('Invalid Google token'));
        }

        $email = $payload['email'];
        $name = $payload['name'];
        $googleId = $payload['sub'];

        // 检查用户是否已存在
        $user = \app\api\model\kuerp\KuerpUser::where('google_id', $googleId)->find();
        if (!$user) {
            // 如果用户不存在，则注册新用户
            $user = $this->auth_s->register($email, Random::alnum(), $email, '', [
                'nickname' => $name,
                'google_id' => $googleId,
            ]);
        }

        // 登录用户
        $this->auth_s->direct($user->id);
        $data = ['userinfo' => $this->auth_s->getUserinfo()];
        $this->success(__('Login successful'), $data);
    }

    /**
     * Facebook 登录
     *
     * @ApiMethod (POST)
     * @param string $token Facebook 返回的 Access Token
     */
    public function facebookLogin()
    {
        $accessToken = $this->request->post('token');
        if (!$accessToken) {
            $this->error(__('Invalid parameters'));
        }

        // 获取代理配置（如果有的话）
        $guzzleInfo = Config::get('facebook.guzzle') ?: null;
        // var_dump($guzzleInfo);exit;
        
        // 配置 Facebook SDK
        $fbConfig = [
            'app_id' => Config::get('facebook.app_id'),
            'app_secret' => Config::get('facebook.app_secret'),
            'default_graph_version' => 'v12.0',
        ];
        
        // 如果有代理配置，则设置 http_client_handler
        if ($proxy = ($guzzleInfo['proxy'] ?? null)) {
            $verifySsl = Config::get('facebook.verify_ssl', true);
            $fbConfig['http_client_handler'] = new FacebookCurlHttpClient($proxy, $verifySsl);
        }

        // 验证 Facebook Access Token
        $fb = new \Facebook\Facebook($fbConfig);

        try {
            $response = $fb->get('/me?fields=id,name,email', $accessToken);
            $userNode = $response->getGraphUser();
        } catch (\Exception $e) {
            $this->error(__('Facebook API error: %s', $e->getMessage()));
        }

        $facebookId = $userNode->getId();
        $email = $userNode->getEmail();
        $name = $userNode->getName();

        // 检查用户是否已存在
        $user = \app\api\model\kuerp\KuerpUser::where('facebook_id', $facebookId)->find();
        if (!$user) {
            // 如果用户不存在，则注册新用户
            $user = $this->auth_s->register($email, Random::alnum(), $email, '', [
                'nickname' => $name,
                'facebook_id' => $facebookId,
            ]);
        }

        // 登录用户
        $this->auth_s->direct($user->id);
        $data = ['userinfo' => $this->auth_s->getUserinfo()];
        $this->success(__('Login successful'), $data);
    }
}
